package com.zsh.rabbitmq.three;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.zsh.rabbitmq.utils.RabbitMQUtils;
import com.zsh.rabbitmq.utils.SleepUtils;

/**
 * @author zsh
 * @Description 消费者02 消费手动应答时不丢失，放回队列重新消费
 * @create 2022-04-26 18:38
 */
public class Work03 {
    public static final String TASK_QUEUE_NAME = "ack_queue";

    //接收消息
    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtils.getChannel();
        System.out.println("c2(时间长)等待接收消息。。。。");

        //声明 接收消息 lambda 表达式
        DeliverCallback deliverCallback = (consumerTag, msg) -> {
            //睡
            SleepUtils.sleep(30);
            String msgString = new String(msg.getBody());
            System.out.println("接收到的消息：" + msgString);
            //手动应答
            /* 参数列表
            1. 消息标识
            2. 是否批量应答 true 批量、false 不批量
             */
            channel.basicAck(msg.getEnvelope().getDeliveryTag(),false);
        };

        //声明 取消消息 lambda 表达式
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println(consumerTag + "消息被取消");
        };

        //设置不公平分发,预取值
        int prefetchCount = 5;
        channel.basicQos(prefetchCount);

        //采用手动应答
        boolean autoAck = false;
        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);

    }
}
